import { ref } from "vue"
import store from "@/store"
import { defineStore } from "pinia"
import { usePermissionStore } from "./permission"
import { useTagsViewStore } from "./tags-view"
import { useSettingsStore } from "./settings"
// import { setAccount, getAccount, removeAccount } from "@/utils/cache/cookies"
import { getToken, removeToken, setToken, setPermissionsBtns, removePermissionsBtns, getPassword } from "@/utils/cache/local-storage"
import router, { resetRouter } from "@/router"
import { loginApi, getUserInfoApi, refreshTokenApi } from "@/api/login"
import { type LoginRequestData } from "@/api/login/types/login"
import { type RouteRecordRaw } from "vue-router"
import routeSettings from "@/config/route"
import { ElMessage } from "element-plus"
import { decryptAES } from "@/utils/secret"

export const useUserStore = defineStore(
  "user",
  () => {
    const token = ref<any>(getToken() || "")
    const roles = ref<string[]>([])
    const username = ref<string>("")
    const userid = ref<string>("")
    const userinvite = ref<string>("")
    const permissionStore = usePermissionStore()
    const tagsViewStore = useTagsViewStore()
    const settingsStore = useSettingsStore()

    /** 设置角色数组 */
    const setRoles = (value: string[]) => {
      roles.value = value
    }
    /** 登录 */
    const login = async (data: LoginRequestData) => {
      let res: any = await loginApi(data)
      if (res.code == 200) {
        setToken(res.data.token, '', null)
        token.value = res.data.token
        setPermissionsBtns(res.data.permissions)
        console.log(username.value);

      } else if (res.code == 1003 || res.code == 1005) {
        ElMessage.error(res.message)
      }
    }
    /** 注册 */
    const register = async ({ account, pwd }: any) => {
      // const { data } = await registerApi({ account, pwd })
    }
    /** 获取用户详情 */
    const getInfo = async () => {

      const pswd = getPassword()
      if (pswd != null) {
        const secretText = decryptAES(pswd.toString())
        username.value = secretText.split(",")[0]
      }
      // const { data } = await getUserInfoApi()
      roles.value = ["admin"]
      // if(data.root==1) roles.value=["SA","admin"]
      // userid.value = data.id ? data.id : "110"
      // username.value = data.name ? data.name : data.account
      // 验证返回的 roles 是否为一个非空数组，否则塞入一个没有任何作用的默认角色，防止路由守卫逻辑进入无限循环
      // roles.value = data.roles?.length > 0 ? data.roles : routeSettings.defaultRoles
    }
    /** 刷新token */
    const refreshToken = async () => {
      const { valueRefresh, expireTimeRefresh } = getToken()
      let res = await refreshTokenApi({ refreshToken: valueRefresh })
      const { accessToken, refreshToken } = res.data
      setToken(accessToken, refreshToken, expireTimeRefresh)
      token.value = accessToken
    }

    /** 刷新路由 */
    const changeRouter = async () => {
      resetRouter()
      await permissionStore.setRoutes()
      permissionStore.dynamicRoutes.forEach((item: RouteRecordRaw) => {
        router.addRoute(item)
      })
      _resetTagsView()
    }

    /** 切换角色 */
    const changeRoles = async (role: string) => {
      // const newToken = "token-" + role
      // token.value = newToken
      // setToken(newToken)
      // await getInfo()
      // permissionStore.setRoutes(roles.value)
      // resetRouter()
      // permissionStore.dynamicRoutes.forEach((item: RouteRecordRaw) => {
      //   router.addRoute(item)
      // })
      // _resetTagsView()
    }
    /** 退出 */
    const logout = () => {
      removeToken()
      token.value = ""
      username.value = ""
      userid.value = ""
      roles.value = []
      resetRouter()
      _resetTagsView()
      removePermissionsBtns()
    }
    /** 重置 Token */
    const resetToken = () => {
      removeToken()
      token.value = ""
      username.value = ""
      userid.value = ""
      roles.value = []
    }
    /** 重置 Visited Views 和 Cached Views */
    const _resetTagsView = () => {
      if (!settingsStore.cacheTagsView) {
        tagsViewStore.delAllVisitedViews()
        tagsViewStore.delAllCachedViews()
      }
    }
    const createUniqueCode = () => {
      const code = Math.random().toString(36).slice(2)
      return code
    }
    return {
      token,
      roles,
      username,
      userid,
      userinvite,
      setRoles,
      login,
      getInfo,
      changeRoles,
      changeRouter,
      logout,
      resetToken,
      createUniqueCode,
      register,
      refreshToken
    }
  }
  // ,{ persist: true }
)

/** 在 setup 外使用 */
export function useUserStoreHook() {
  return useUserStore(store)
}
